//
//  NewsListViewController.m
//  ShowYork
//
//  Created by hxh on 2021/1/18.
//  Copyright © 2021 hxh. All rights reserved.
//

#import "NewsListViewController.h"
#import "CommonWebViewController.h"
#import "NewsCollectListViewController.h"
#import "NewsSearchViewController.h"
#import "NewsItemViewController.h"
#import "NewsListSegmentedView.h"
#import "NewsTagItemModel.h"
#import "NewsListBannerView.h"
#import "JXPagerView.h"
#import "NewsPageNavView.h"
#import "LessonBannerModel.h"
#import "JXPagerListRefreshView.h"

@interface NewsListViewController ()<JXPagerViewDelegate, JXPagerMainTableViewGestureDelegate,NewsPageNavViewDelegate>
@property (nonatomic,strong)JXPagerListRefreshView *pagerView;

//@property (nonatomic,strong)UIView *line;

@property (nonatomic,strong)NewsListSegmentedView *segmentedView;

@property (nonatomic,copy)NSArray *tagArray;


@property (nonatomic,copy)NSArray *bannerArray;

@property (nonatomic,strong)NewsListBannerView *bannerView;

@property (nonatomic,strong)NewsPageNavView *pageNavView;

@end

@implementation NewsListViewController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    [self findHairlineImageViewUnder:self.navigationController.navigationBar].hidden = YES;
    
    [self.bannerView adjustWhenControllerViewWillAppera];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];

    [self findHairlineImageViewUnder:self.navigationController.navigationBar].hidden = NO;


}

- (NewsListBannerView *)bannerView{
    if (!_bannerView) {
        __weak typeof(self)weakSelf = self;
        _bannerView = [[NewsListBannerView alloc]initWithCompleteBlock:^(NSInteger index) {
         
            LessonBannerModel *model = weakSelf.bannerArray[index];
            
            [weakSelf showBannerDetailWithUrl:model.url];
        }];
    }
    return _bannerView;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setUI];
    
    [self loadDataSource];
    

}
- (void)back{
    [super back];
}

- (void)setUI{
    
    self.isHideNavBar = YES;

    self.navigationItem.leftBarButtonItem = nil;
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.pageNavView = [[NewsPageNavView alloc]initWithDelegate:self];
    
    
    [self.view addSubview:self.pageNavView];
    
    
    self.pagerView = [[JXPagerListRefreshView alloc]initWithDelegate:self];
   
    self.pagerView.mainTableView.gestureDelegate = self;
    self.pagerView.isListHorizontalScrollEnabled = YES;
    self.pagerView.automaticallyDisplayListVerticalScrollIndicator = NO;
    self.pagerView.pinSectionHeaderVerticalOffset = 0;
    [self.view addSubview:self.pagerView];
    
    __weak typeof(self)weakSelf = self;
    self.segmentedView = [[NewsListSegmentedView alloc]initWithCompleteBlock:^(NSInteger index) {
        [weakSelf.pagerView.listContainerView.scrollView setContentOffset:CGPointMake(kScreenW *index, 0) animated:YES];
        [weakSelf.pagerView.listContainerView didClickSelectedItemAtIndex:index];
       
    }];
  
    self.segmentedView.hidden = NO;

    self.pagerView.frame = CGRectMake(0,CGRectGetMaxY(self.pageNavView.frame), kScreenW, kScreenH - CGRectGetMaxY(self.pageNavView.frame));
}

- (void)loadDataSource{
    [self showDataLoadState];
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadTagList];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadBannerSource];
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
    
        [self hideDataLoadLoadState];
        self.segmentedView.itemArray = self.tagArray;
        self.segmentedView.contentScrollView = self.pagerView.listContainerView.scrollView;
        
        [self.bannerView setItemArray:self.bannerArray];
        
        [self.pagerView reloadData];
    });
}

#pragma mark - loadTagList
- (void)loadTagList{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"md5"] = [RPAppManager md5StrWithApi:GetNewsTagList];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetNewsTagList) parames:param success:^(id responseObj) {
        self.tagArray = [NewsTagItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

- (void)loadBannerSource{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"scope"] = @4;
    param[@"md5"] = [RPAppManager md5StrWithApi:GetBanner];
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetBanner) parames:param success:^(id responseObj) {
        self.bannerArray = [LessonBannerModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}



//#pragma mark - JXPagerMainTableViewGestureDelegate
- (BOOL)mainTableViewGestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    //禁止categoryView左右滑动的时候，上下和左右都可以滚动
    return [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]] && [otherGestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]];
}
#pragma mark - JXPagerViewDelegate

- (UIView *)tableHeaderViewInPagerView:(JXPagerView *)pagerView {
    if (self.bannerArray.count == 0) {
        return [UIView new];
    }else{
        return self.bannerView;
    }
}

- (NSUInteger)tableHeaderViewHeightInPagerView:(JXPagerView *)pagerView {
    if (self.bannerArray.count == 0) {
        return 0;
    }
    // 宽高比
    CGFloat rate = 134.0/343.0;
    CGFloat itemW = kScreenW - 32;
    CGFloat itemH = itemW * rate;
    // 内容高度+上下间距
    return itemH + 36;
}
- (NSUInteger)heightForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    if (self.tagArray.count == 0) {
        return 0;
    }

    return 44.0f;
}

- (UIView *)viewForPinSectionHeaderInPagerView:(JXPagerView *)pagerView {
    return self.segmentedView;
}
- (NSInteger)numberOfListsInPagerView:(JXPagerView *)pagerView {
    return self.tagArray.count;
}

- (id<JXPagerViewListViewDelegate>)pagerView:(JXPagerView *)pagerView initListAtIndex:(NSInteger)index {
    
    NewsTagItemModel *itemModel = self.tagArray[index];
    
    NewsItemViewController *listVC = [[NewsItemViewController alloc]initWithNewsTagItemModel:itemModel];
    
    return listVC;
}

- (void)pagerView:(JXPagerView *)pagerView mainTableViewDidScroll:(UIScrollView *)scrollView{
    
  
}

#pragma mark - NewsPageNavViewDelegate
- (void)popViewController{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)showSearch{
    NewsSearchViewController *searchVC = [[NewsSearchViewController alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
}
- (void)showCollectList{
    
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    NewsCollectListViewController *listVC = [[NewsCollectListViewController alloc]init];
    [self.navigationController pushViewController:listVC animated:YES];
}

#pragma mark - other
- (UIImageView *)findHairlineImageViewUnder:(UIView *)view
{
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0)
    {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

- (void)showBannerDetailWithUrl:(NSString *)url{
    // 除非首末空格
    url = [url cl_removeSpaceString];
    // 解析
    NSDictionary *param = [self dictionaryWithUrlString:url];
    
    if ([url hasPrefix:@"https://"] || [url hasPrefix:@"http://"]) {
        url = [url stringByRemovingPercentEncoding];
        NSRange range = [url rangeOfString:@"?"];
        if (range.location == NSNotFound) {
            if ([url containsString:@"isApp=true"]) {
                url = [NSString stringWithFormat:@"%@",url];
            }else{
                url = [NSString stringWithFormat:@"%@?isApp=true",url];
            }
        }else{
            if ([url containsString:@"isApp=true"]) {
                url = [NSString stringWithFormat:@"%@",url];
            }else{
                url = [NSString stringWithFormat:@"%@&isApp=true",url];
            }
        }
        CommonWebViewController *webVC = [[CommonWebViewController alloc]init];
        webVC.webUrl = url;
        webVC.isDark = NO;
        [self.navigationController pushViewController:webVC animated:YES];
        return;
    }
    
    // web 多种情况
    if ([url containsString:@"local://ddup.app/web"]) {
        if (param[@"url"] != nil && [param[@"url"] isKindOfClass:[NSString class]]) {
            NSString *url = param[@"url"];
            url = [url stringByRemovingPercentEncoding];
            NSRange range = [url rangeOfString:@"?"];
            if (range.location == NSNotFound) {
                if ([url containsString:@"isApp=true"]) {
                    url = [NSString stringWithFormat:@"%@",url];
                }else{
                    url = [NSString stringWithFormat:@"%@?isApp=true",url];
                }
            }else{
                if ([url containsString:@"isApp=true"]) {
                    url = [NSString stringWithFormat:@"%@",url];
                }else{
                    url = [NSString stringWithFormat:@"%@&isApp=true",url];
                }
            }
            CommonWebViewController *webVC = [[CommonWebViewController alloc]init];
            webVC.webUrl = url;
            webVC.isDark = NO;
            [self.navigationController pushViewController:webVC animated:YES];
        }
    }
}

-(NSDictionary *)dictionaryWithUrlString:(NSString *)urlStr
{
    if (urlStr && urlStr.length && [urlStr rangeOfString:@"?"].length == 1) {
        NSArray *array = [urlStr componentsSeparatedByString:@"?"];
        if (array && array.count == 2) {
            NSString *paramsStr = array[1];
            if (paramsStr.length) {
                NSMutableDictionary *paramsDict = [NSMutableDictionary dictionary];
                NSArray *paramArray = [paramsStr componentsSeparatedByString:@"&"];
                for (NSString *param in paramArray) {
                    if (param && param.length) {
                        NSArray *parArr = [param componentsSeparatedByString:@"="];
                        if (parArr.count == 2) {
                            [paramsDict setObject:parArr[1] forKey:parArr[0]];
                        }
                    }
                }
                return paramsDict;
            }else{
                return nil;
            }
        }else{
            return nil;
        }
    }else{
        return nil;
    }
}


@end
